package com.ysc.plugin.utility.photo.open

import android.app.Activity
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import androidx.core.content.FileProvider
import com.ysc.plugin.common.ActivityRequestCode
import com.ysc.plugin.common.PermissionsRequestCode
import com.ysc.plugin.common.PictureType
import com.ysc.plugin.common.abstract.ManagerModule
import com.ysc.plugin.utility.photo.PhotoManger
import com.ysc.plugin.utility.photo.clip.ClipPhoto
import org.json.JSONObject
import java.io.File
import java.io.OutputStream
import java.text.SimpleDateFormat
import java.util.*

class OpenPhoto(activity: Activity) : ManagerModule() {
    private val mActivity:Activity = activity
    private var mImagePath: String = ""
    private var mStorageDirName:String = "demo"
    private var mPictureName:String = "demo"
    private var mPictureType:String = PictureType.jpeg.name
    private var mPictureRotate:Float = 90f
    private var mCurrentFunction = fun (){}

    init {
        var dff = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        dff.setTimeZone(TimeZone.getTimeZone("GMT+08"))
        mPictureName = dff.format(Date())
    }

    private fun checkPermission():Boolean
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            var status = mActivity.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            if(status != PackageManager.PERMISSION_GRANTED)
            {
                return false
            }
        }
        return true
    }

    fun openDefaultCamera(data:String){
        var pictureRotate: Float = 90f
        var pictureName: String = ""
        var storageDirName: String = ""
        var pictureType: String = PictureType.jpeg.name
        if (data!=null && !data.isEmpty())
        {
            var decodeData = JSONObject(data)
            if(decodeData.has("pictureRotate"))
                pictureRotate = (decodeData["pictureRotate"] as Int).toFloat()
            if(decodeData.has("pictureName"))
                pictureName = decodeData["pictureName"] as String
            if(decodeData.has("storageDirName"))
                storageDirName = decodeData["storageDirName"] as String
            if(decodeData.has("pictureType"))
                pictureType = decodeData["pictureType"] as String
        }
        if(checkPermission())
        {
            mPictureRotate = pictureRotate
            mPictureType = pictureType
            if(storageDirName != "")
                mStorageDirName = storageDirName
            if(pictureName != "")
                mPictureName = pictureName
            val intent: Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            setActivityResult(true)
            var extStorageDirectory = mActivity.getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString()
            var filename:String = mPictureName + "." + mPictureType
            mImagePath = extStorageDirectory + "/" + filename
            var file = File(mImagePath)
            var t = FileProvider.getUriForFile(
                mActivity,
                mActivity.packageName + ".fileprovider",
                file
            )
            intent.putExtra(MediaStore.EXTRA_OUTPUT, t)
            mActivity.startActivityForResult(
                intent,
                ActivityRequestCode.REQUEST_PHOTO_OPEN_CAMERA.ordinal
            )
        }else{
            var permissions:Array<String> = arrayOf(
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                android.Manifest.permission.CAMERA
            )
            setPermissionsResult(true)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                mActivity.requestPermissions(
                    permissions,
                    PermissionsRequestCode.REQUEST_WRITE_EXTERNAL_STORAGE.ordinal
                )
            }
            mCurrentFunction = fun (){
                openDefaultCamera(data)
            }
        }
    }

    private fun savePictureToAlbum()
    {
        var contentResolver = mActivity.contentResolver
        var contentValues = ContentValues()
       // contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/" + mStorageDirName)
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, mPictureName + "." + mPictureType)
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/" + mPictureType)
        var uri = contentResolver.insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            contentValues
        )
        var outputStream: OutputStream?
        try {
            outputStream = uri?.let { contentResolver.openOutputStream(it) }
            var bitmap = BitmapFactory.decodeFile(mImagePath)
            var newBitmap = PhotoManger.getInstance()?.rotaingImageView(mPictureRotate, bitmap)
            newBitmap?.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
            outputStream?.flush()
            outputStream?.close()
            var t = PhotoManger.getInstance()?.getManagerModuleByName("ClipPhoto") as ClipPhoto
            t.photoClip(mImagePath)

        } catch (e: Exception) {
            e.printStackTrace();
            Log.d("savePictureToAlbum", "Exception=" + e.message);
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if(resultCode == Activity.RESULT_OK) {
            if (requestCode == ActivityRequestCode.REQUEST_PHOTO_OPEN_CAMERA.ordinal) {
                savePictureToAlbum()
                setActivityResult(false)
            }
        }
    }

    override fun onDestroy() {

    }

    override fun getHelp(): String {
        return "command:photo;\n" +
                "category:OpenPhoto;\n" +
                "operate:{\n" +
                "  openDefaultCamera:打开默认相机进行拍照,\n" +
                "    parameter:{\n" +
                "      pictureRotate:设置拍照后图片旋转角度\n" +
                "      pictureName:保存图片的名称\n" +
                "      storageDirName:图片存储目录文件夹名称\n" +
                "      pictureType:图片格式\n" +
                "    }\n" +
                "}"
                //"{'command':'photo','category':'OpenPhoto','operate':'openDefaultCamera','parameter':'{'pictureRotate':90,'pictureName':'ysc','storageDirName':'Ysc','pictureType':'jpeg'}'}"
    }

    override fun getName(): String {
        return "OpenPhoto"
    }

    override fun getVersion(): String {
        return "1.0.0"
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        setPermissionsResult(false)
        if(requestCode == PermissionsRequestCode.REQUEST_WRITE_EXTERNAL_STORAGE.ordinal && grantResults[0] == PackageManager.PERMISSION_GRANTED)
        {
            mCurrentFunction()
            mCurrentFunction = fun (){}
        }
    }
}